function msToTime(secondsNumber) {
    // 初始化变量
    let hours = Math.floor(secondsNumber / 3600),
        minutes = Math.floor((secondsNumber % 3600) / 60),
        seconds = Math.floor(secondsNumber % 60);

    // 确保时间数值为两位数
    hours = (hours < 10 ? "0" : "") + hours;
    minutes = (minutes < 10 ? "0" : "") + minutes;
    seconds = (seconds < 10 ? "0" : "") + seconds;

    // 返回格式化的时间字符串
    return `${hours}${minutes}${seconds}`;
}

function msToTime2(secondsNumber) {
    // 初始化变量
    let hours = Math.floor(secondsNumber / 3600),
        minutes = Math.floor((secondsNumber % 3600) / 60),
        seconds = Math.floor(secondsNumber % 60);

    // 确保时间数值为两位数
    hours = (hours < 10 ? "0" : "") + hours;
    minutes = (minutes < 10 ? "0" : "") + minutes;
    seconds = (seconds < 10 ? "0" : "") + seconds;

    // 返回格式化的时间字符串
    return `${hours}:${minutes}:${seconds}`;
}

function takeScreenshot() {
    // 获取video
    var video = $('#js-video')[0];
    if (!video) return;

    try {
        // 设置canvas和context
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;

        // 在video的当前播放时间点绘制截图到canvas
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        // 右下角绘制时间
        var timeStr2 = msToTime2(video.currentTime); // 获取当前播放时间
        ctx.font = '24px Arial';
        ctx.fillStyle = 'yellow';
        ctx.fillText(timeStr2, canvas.width - 110, canvas.height - 30);

        var timeStr = msToTime(video.currentTime);
        var titleStr = document.title.replace(/\.[^/.]+$/, "");
        var fileName = `${titleStr}_${timeStr}.jpg`;  // 设置下载的文件名

        // downloadImage(canvas, fileName);
        uplaodImage(canvas, fileName);

    } catch (e) {
        console.log(e);
    }
}

function downloadImage(canvas, fileName){
    // 将canvas内容转换为Data URL
    var dataURL = canvas.toDataURL('image/jpg');

    // 创建一个临时的<a>元素用于下载
    var link = document.createElement('a');
    link.href = dataURL;
    link.download = fileName;  // 设置下载的文件名

    // 触发点击事件以下载文件
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

function uplaodImage(canvas, fileName){
    // 将canvas内容转换为Blob对象
    canvas.toBlob(function(blob) {
        // 创建一个FormData对象来存储文件数据
        var formData = new FormData();
        formData.append('file', blob, fileName);  // 'image'是服务器端接收文件的字段名

        // 使用Fetch API发送POST请求到服务器
        fetch('http://localhost:10169/upload/preview', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())  // 假设服务器返回JSON响应
            .then(data => {
                console.log('Upload success:', data);
                // 在这里处理服务器返回的响应数据
            })
            .catch(error => {
                console.error('Upload error:', error);
            });
    }, 'image/jpeg', 0.6);  // 指定图片类型为PNG
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

function isSeekFinsh(video) {
    let buf = video.buffered;
    let currentTime = video.currentTime;

    for (var i = 0; i < buf.length; i++) {
        var start = buf.start(i),
            end = buf.end(i);

        if (currentTime >= start && end >= currentTime && !video.seeking) {
            return true;
        }
    }

    return false;
}

async function takeScreenshotAtTime(playTime) {
    // 获取video
    var video = $('#js-video')[0];
    if (!video) return;

    var $video_box = $('#js-video_box');
    var $play = $video_box.find('[btn="play"]');

    try {
        if (video.paused) {
            $play.trigger('click');
        }
        // video.currentTime =Math.round(duration * (key - 48) / 10);
        video.currentTime = playTime;

        for (let i = 0; i < 5; i++) {
            await sleep(1000);

            if (isSeekFinsh(video)) {
                break;
            }
        }

        // 设置canvas和context
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;

        // 在video的当前播放时间点绘制截图到canvas
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        // 右下角绘制时间
        var timeStr2 = msToTime2(video.currentTime); // 获取当前播放时间
        ctx.font = '24px Arial';
        ctx.fillStyle = 'yellow';
        ctx.fillText(timeStr2, canvas.width - 110, canvas.height - 30);

        // 将canvas内容转换为Data URL
        var dataURL = canvas.toDataURL('image/jpg', 0.6);
        canvas.toBlob()

        var timeStr = msToTime(video.currentTime);
        var titleStr = document.title.replace(/\.[^/.]+$/, "");

        // 创建一个临时的<a>元素用于下载
        var link = document.createElement('a');
        link.href = dataURL;
        link.download = `${titleStr}_${timeStr}.jpg`;  // 设置下载的文件名

        // 触发点击事件以下载文件
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

    } catch (e) {
        console.log(e);
    }
}

async function startAutoScrreenshot() {
    var video = $('#js-video')[0];
    if (!video) return;

    let duration = video.duration;
    for (let curTm = 60; curTm < duration;) {
        await takeScreenshotAtTime(curTm);

        curTm += 10 * 60;
    }

    alert('获取预览图结束！！！');
}

async function startAutoScrreenshotSamll() {
    var video = $('#js-video')[0];
    var $video_box = $('#js-video_box');
    var $play = $video_box.find('[btn="play"]');

    if (!video) return;

    try {
        let duration = video.duration;
        let rowJiange = 5 * 60;
        let rowCount = Math.floor(duration / rowJiange);
        let colCount = 3;
        let jiange = Math.floor(rowJiange / colCount);

        let video_width = 500;
        let video_height = Math.floor(video_width * (video.videoHeight / video.videoWidth));

        // 设置canvas和context
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        canvas.width = (video_width + 1) * colCount + 1;
        canvas.height = (video_height + 1) * rowCount + 1;

        let curTm = 60;
        for (let i = 0; i < rowCount; i++) {
            for (let j = 0; j < colCount; j++) {
                if (curTm >= duration) {
                    break;
                }
                await screenshotAtTime(curTm, (video_width + 1) * j, (video_height + 1) * i);

                curTm += jiange;
            }
        }

        screenshotEnd();

        async function screenshotAtTime(playTime, dx, dy) {
            if (video.paused) {
                $play.trigger('click');
            }
            // video.currentTime =Math.round(duration * (key - 48) / 10);
            video.currentTime = playTime;

            for (let i = 0; i < 5; i++) {
                await sleep(1000);

                if (isSeekFinsh(video)) {
                    break;
                }
                video.currentTime += 5;
            }

            // 在video的当前播放时间点绘制截图到canvas
            ctx.drawImage(video, dx, dy, video_width, video_height);
            // 右下角绘制时间
            var timeStr2 = msToTime2(video.currentTime); // 获取当前播放时间
            ctx.font = '16px Arial';
            ctx.fillStyle = 'yellow';
            ctx.fillText(timeStr2, dx + video_width - 80, dy + video_height - 10);
        }

        function screenshotEnd() {
            // 将canvas内容转换为Data URL
            var dataURL = canvas.toDataURL('image/jpeg', 0.6);

            const titleStr = document.title.replace(/\.[^/.]+$/, "").replace(".HD", "").replace(".FHD", "").replace(".txt", "").replace(/[a-zA-Z0-9]+\.[a-zA-Z]{2,3}/g, '');
            const regex = /[a-zA-Z]{2,5}-?[0-9]{2,5}/;
            const match = titleStr.match(regex);
            let avcode = null;
            if (match && match[0]) {
                avcode = match[0].toUpperCase();
            }

            if (!avcode) {
                avcode = titleStr;
            }

            // 创建一个临时的<a>元素用于下载
            var link = document.createElement('a');
            link.href = dataURL;
            link.download = `${avcode}-full.jpg`;  // 设置下载的文件名

            // 触发点击事件以下载文件
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

        }

    } catch (e) {
        console.log(e);
    } finally {
        alert('获取预览图结束！！！');
    }

}

takeScreenshot();
// startAutoScrreenshot();
// startAutoScrreenshotSamll();